package com.itheima.prize.commons.db.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.itheima.prize.commons.db.entity.CardUser;
import com.itheima.prize.commons.db.service.CardUserService;
import com.itheima.prize.commons.db.mapper.CardUserMapper;
import com.itheima.prize.commons.utils.ApiResult;
import com.itheima.prize.commons.utils.PasswordUtil;
import com.itheima.prize.commons.utils.RedisUtil;
import io.netty.util.internal.ObjectUtil;
import org.apache.commons.lang3.ObjectUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import sun.java2d.marlin.ArrayCacheConst;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;


/**
 * @author shawn
 * @description 针对表【card_user(会员信息表)】的数据库操作Service实现
 * @createDate 2023-12-26 11:58:48
 */
@Service
public class CardUserServiceImpl extends ServiceImpl<CardUserMapper, CardUser>
        implements CardUserService {

    @Autowired
    private RedisUtil redisUtil;

    /**
     * 登录
     *
     * @param account
     * @param md5password
     * @return
     */
    @Override
    public ApiResult Login(HttpServletRequest request,String account, String md5password) {


        //1.查询用户
        QueryWrapper<CardUser> cardQueryWrapper = new QueryWrapper<CardUser>()
                .eq("uname",account);
        CardUser cardUser = baseMapper.selectOne(cardQueryWrapper);

        //2.校验用户是否存在
        if (cardUser == null) {
            return new ApiResult<>(-1, "账号和密码不能为空", null);
        }

        // 获取当前用户的密码错误次数
        Integer errorCount = (Integer) redisUtil.get(account);
        if (errorCount == null) {
            errorCount = 0;
        }

        // 超过最大次数
        if (errorCount >= 5) {
            return new ApiResult<>(0, "登录超过最大重试次数，请5分钟后重试", null);
        }

        // 校验用户密码是否正确
        if (!cardUser.getPasswd().equals(md5password)){
            errorCount++;
            redisUtil.set(account, errorCount, 5);
            return new ApiResult<>(0, errorCount >= 5 ? "登录超过最大重试次数，请5分钟后重试" : "密码错误", null);
        }

        // 登录成功删除缓存
        redisUtil.del(account);

        cardUser.setPasswd(null);

        //4.登录成功
        HttpSession session = request.getSession();
        session.setAttribute("user",cardUser);

        return new ApiResult(1, "登录成功", cardUser);
    }
}




